package com.lvdp.utils;

import cn.hutool.core.bean.BeanUtil;
import com.lvdp.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.lvdp.utils.RedisConstants.LOGIN_USER_KEY;
import static com.lvdp.utils.RedisConstants.LOGIN_USER_TTL;

/**
 * Description: 刷新token拦截器 所有的路径 都进行刷新token处理
 * Date:      2022/11/2 22:57
 * author:    LPH
 * version:   V1.0
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取请求头的参数
        String token = request.getHeader("authorization");
        // 2. 从redis中获取值
        String tokenKey = LOGIN_USER_KEY + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(tokenKey);
        // 3. 将查到的userMap转回为对象
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        // 4. 将userDTO存在ThreadLocal中
        UserHolder.saveUser(userDTO);
        // 5. 刷新token的有效期
        stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.SECONDS);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
